package com.ho1ho.springboot.framework.core.utils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

// http://www.baeldung.com/spring-app-setup-with-csv-files
// https://github.com/FasterXML/jackson-dataformats-text/tree/master/csv
//
// This utility will skip the first DATA line, not the first line(The first line is header).
public class CsvUtils {
	public static <T> List<T> loadObjectList(Class<T> type, MultipartFile multipartFile) throws IOException {
		// CsvSchema schema = CsvSchema.builder()
		// .setColumnSeparator(',')
		// .addColumn("Id")
		// .addColumn("name").build();
		CsvSchema bootstrapSchema = CsvSchema.emptySchema().withHeader();
		CsvMapper mapper = new CsvMapper();
		mapper.setDateFormat(new SimpleDateFormat("yyyy/MM/dd"));
		// File file = new ClassPathResource(fileName).getFile();
		MappingIterator<T> readValues = mapper.readerFor(type).with(bootstrapSchema).readValues(multipartFile.getInputStream());
		for (int i = 0; i < 1; i++) {
			if (readValues.hasNext()) {
				readValues.next();
			}
		}
		return readValues.readAll();
	}
}
